<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色限列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="adddialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>

      <!-- 角色列表区域 -->
      <el-table :data="rolelist" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item, i) in scope.row.children"
              :key="item.id"
              :class="['btn', i === 0 ? 'btntop' : '', 'vcenter']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item.id)">
                  {{ item.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二三级权限 -->
              <el-col :span="19">
                <el-row
                  type="success"
                  v-for="item1 in item.children"
                  :key="item1.id"
                  :class="[i !== 0 ? 'btntop' : '', 'vcenter']"
                >
                  <el-col>
                    <el-tag
                      closable
                      @close="removeRightById(scope.row, item1.id)"
                      type="success"
                    >
                      {{ item1.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="item2 in item1.children"
                      :key="item2.id"
                      class="warning"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-edit"
              type="primary"
              size="mini"
              @click="editRoleRight(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              icon="el-icon-delete"
              type="danger"
              size="mini"
              @click="deleterole(scope.row.id)"
            >
              删除
            </el-button>
            <el-button
              icon="el-icon-setting"
              type="warning"
              size="mini"
              @click="showSetRightDialog(scope.row)"
            >
              分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色区域 -->
    <el-dialog title="添加角色" :visible.sync="adddialogVisible" width="50%">
      <el-form ref="addRef" :model="addList" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="addList.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addList.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑窗口区域 -->
    <el-dialog title="编辑角色" :visible.sync="editdialogVisible" width="50%">
      <el-form ref="editRef" :model="editList" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="editList.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editList.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="edit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightdialogVisible"
      width="50%"
    >
      <el-tree
        :data="rightList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all="true"
        :default-checked-keys="defkeys"
        ref="treeRef"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      rolelist: [],
      editdialogVisible: false,
      editList: {},
      addList: {
        roleName: '',
        roleDesc: ''
      },
      adddialogVisible: false,
      addListRules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      setRightdialogVisible: false,
      rightList: [],
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中权限
      defkeys: [],
      // 获取编辑权限的id
      roleId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 修改权限并上传服务器
    async allotRight () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedNodes()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        this.$message.error('修改权限失败')
      }
      this.$message.success('修改权限成功')
      this.setRightdialogVisible = false
      this.getRolesList()
    },

    // 递归获取所有三级权限id并保存到defkeys
    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    async showSetRightDialog (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      } else {
        this.rightList = res.data
        this.getLeafKeys(role, this.defkeys)
      }
      this.setRightdialogVisible = true
    },
    async removeRightById (role, rightId) {
      const result = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      } else {
        this.$message.success('删除成功')
      }
      role.children = res.data
    },
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      } else {
        this.rolelist = res.data
      }
    },
    editRoleRight (msg) {
      this.editdialogVisible = true
      this.editList = msg
    },
    async edit () {
      const { data: res } = await this.$http.put(`roles/${this.editList.id}`, { roleName: this.editList.roleName, roleDesc: this.editList.roleDesc })
      if (res.meta.status !== 200) {
        return this.$message.error('修改失败')
      } else {
        this.$message.success('修改成功')
        this.editdialogVisible = false
        this.getRolesList()
      }
    },
    async add () {
      this.$refs.addRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post('roles', this.addList)
          if (res.meta.status === 201) {
            this.$message.success('添加成功')
            this.adddialogVisible = false
            this.getRolesList()
          } else {
            return this.$message.error('添加失败')
          }
        }
      })
    },
    async deleterole (id) {
      const { data: res } = await this.$http.delete(`roles/${id}`)
      if (res.meta.status === 200) {
        this.$message.success('删除成功')
        this.getRolesList()
      } else {
        this.$message.error('删除失败')
      }
    }
  },
  watch: {
    setRightdialogVisible (n) {
      if (!n) {
        this.defkeys = []
      }
    },
    editdialogVisible (n) {
      if (!n) {
        this.$refs.editRef.resetFields()
      }
    },
    adddialogVisible (n) {
      if (!n) {
        this.$refs.addRef.resetFields()
      }
    }
  }
}
</script>

<style>
.el-tag {
  margin: 7px;
}
.btn {
  border-bottom: 1px solid #eee;
}
.btntop {
  border-top: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
